<?php
/**
 * Created by PhpStorm.
 * User: zanboon-201
 * Date: 2019/3/19
 * Time: 11:37
 */

namespace app\generate\controller;
use think\Controller;
use think\Db;
use think\exception\PDOException;

class Index extends Controller
{
    /**
     * @title 首页
     * @description 首页
     * @author 开发者（宋晓文）
     * @url /generate/Index/index
    **/
    public function index(){
        $index_model=new \app\generate\model\Index();
        $create_generate_database = $index_model->create_generate_database();


        //模板输出
        return $this->fetch('/view/index');
    }


    /**
     * @title 添加分组
     * @description 添加分组
     * @author 开发者（宋晓文）
     * @url /generate/Index/add_group
    **/
    public function table(){
        //模板输出
        return $this->fetch('/view/table');
    }

    /**
     * @title 添加控制器
     * @description 添加控制器
     * @author 开发者（宋晓文）
     * @url /generate/Index/add_function
     **/
    public function add_function(){
        //模板输出
        return $this->fetch('/view/add_function');
    }

    /**
     * @title 验证器
     * @description 验证器
     * @author 开发者（宋晓文）
     * @url /generate/Index/validate_list
     **/
    public function validate_list(){
        //模板输出
        return $this->fetch('/view/validate_list');
    }
    /**
     * @title 控制器页面
     * @description 控制器页面
     * @author 开发者（宋晓文）
     * @url /generate/Index/controller_list
     **/
    public function controller_list(){
        //模板输出
        return $this->fetch('/view/controller_list');
    }
    /**
     * @title 编辑接口页面
     * @description 编辑接口页面
     * @author 开发者（宋晓文）
     * @url /generate/Index/edit_function
     **/
    public function edit_function(){
        //模板输出
        return $this->fetch('/view/edit_function');
    }

    /**
     * @title 数据表修改页面
     * @description 数据表修改页面
     * @author 开发者（宋晓文）
     * @url /generate/Index/table_edit
     **/
    public function table_edit(){
        //模板输出
        return $this->fetch('/view/table_edit');
    }

    /**
     * @title Vue代码生成页面
     * @description Vue代码生成页面
     * @author 开发者（宋晓文）
     * @url /generate/Index/vue
     **/
    public function vue(){
        //模板输出
        return $this->fetch('/view/vue');

    }

    /**
     * @title 一键添加function
     * @description 一键添加function
     * @author 开发者（宋晓文）
     * @url /generate/Index/auto_create_function
     **/
    public function auto_create_function(){
        $input = input();
        $rule = [
            'table_id' => ['require','number'],
        ];
        $vmsg = [
            'require' => '不能为空',
            'number' => '必须是数字'
        ];
        $validate = new \think\Validate($rule,$vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg']='校验失败';
            $msg['validate']=$validate->getError();
            return $this->errorJson($msg);
        }

        $model = new \app\generate\model\Index();
        $create = $model->auto_create_function($input['table_id']);
        if (!$create){
            $msg['msg'] = '添加失败！';
            return $this->errorJson($msg);
        }else{
            $msg['msg'] = '添加成功！';
            return $this->successJson($msg);
        }
    }

    /**
     * @title 字段检测
     * @description 字段检测（generate & database）
     * @author 开发者（宋晓文）
     * @url /generate/Index/check_field
     **/
    public function check_field(){
        $input = input();
        $rule = [
            'table_id' => ['require','number'],
        ];
        $vmsg = [
            'require' => '不能为空',
            'number' => '必须是数字'
        ];
        $validate = new \think\Validate($rule,$vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg']='校验失败';
            $msg['validate']=$validate->getError();
            return $this->errorJson($msg);
        }
        $model = new \app\generate\model\Index();

        $res = $model->check_field($input['table_id']);

        if (!empty($res['g_null'])){
            Db::table('zb_generate.tp_field')->insertAll($res['g_null']);
        }
        if (!$res){
            $msg['msg'] = '检测失败！';
            $msg['data'] = $res;
            return $this->errorJson($msg);
        }else{
            $msg['msg'] = '检测成功！';
            $msg['data'] = $res;
            return $this->successJson($msg);
        }

    }
    /**
     * @title 批量删除字段（generate）
     * @description 批量删除字段（generate）
     * @author 开发者（宋晓文）
     * @url /generate/Index/delete_field_list
     **/
    public function delete_field_list(){
        $input = input();
        $rule = [
            'field_list' => ['require'],
        ];
        $vmsg = [
            'require' => '不能为空',
        ];
        $validate = new \think\Validate($rule,$vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg']='校验失败';
            $msg['validate']=$validate->getError();
            return $this->errorJson($msg);
        }
        $id_list=[];
        foreach ($input['field_list'] as $k=>$v){
            if (!empty($v['id'])){
                array_push($id_list, $v['id']);
            }
        }
        if (empty($id_list)){
            $msg['msg']='无可用数据';
            return $this->errorJson($msg);
        }
        $model = new \app\generate\model\Index();
        $res = $model->delete_field_list($id_list);

        $msg['res'] = $res;
        $msg['msg'] = '删除成功！';
        return $this->successJson($msg);
    }
    /**
     * @title 批量添加字段（database）
     * @description 批量添加字段（database）
     * @author 开发者（宋晓文）
     * @url /generate/Index/add_field_to_database
     **/
    public function add_field_to_database(){
        $input = input();
        $rule = [
            'table_id' => ['require','number'],
            'field_list' => ['require'],
        ];
        $vmsg = [
            'require' => '不能为空',
        ];
        $validate = new \think\Validate($rule,$vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg']='校验失败';
            $msg['validate']=$validate->getError();
            return $this->errorJson($msg);
        }

        $table = Db::table('zb_generate.tp_table')->find($input['table_id']);
        $database = Db::table('zb_generate.tp_model')->find($table['model_id']);
        if(empty($table) || empty($database)){
            $msg['msg']='table_id无可用数据获取';
            return $this->successJson($msg);
        }

        $model = new \app\generate\model\Index();
        $res = $model->add_field_to_database("zb_".$database['db_name'],$table['table_prefix'].$table['table_name'],$input['field_list']);

        $msg['res'] = $res;
        $msg['msg'] = '数据库添加字段成功！';
        return $this->successJson($msg);
    }
    /**
     * @title 批量重建字段（database）
     * @description 批量重建字段（database）
     * @author 开发者（宋晓文）
     * @url /generate/Index/database_rebuild_field
     **/
    public function database_rebuild_field()
    {
        $input = input();
        $rule = [
            'table_id' => ['require', 'number'],
            'field_list' => ['require'],
        ];
        $vmsg = [
            'require' => '不能为空',
        ];
        $validate = new \think\Validate($rule, $vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg'] = '校验失败';
            $msg['validate'] = $validate->getError();
            return $this->errorJson($msg);
        }

        $table = Db::table('zb_generate.tp_table')->find($input['table_id']);
        $database = Db::table('zb_generate.tp_model')->find($table['model_id']);
        if (empty($table) || empty($database)) {
            $msg['msg'] = 'table_id无可用数据获取';
            return $this->successJson($msg);
        }

        $data = [];
        foreach ($input['field_list'] as $k=>$v){
            if (!empty($v['generate'])){
                array_push($data,$v['generate']);
            }
        }
        $index_model = new \app\generate\model\Index();
        $drop_res = $index_model->del_field_to_database("zb_".$database['db_name'],$table['table_prefix'].$table['table_name'],$data);
        $add_res = $index_model->add_field_to_database("zb_".$database['db_name'],$table['table_prefix'].$table['table_name'],$data);

        if($drop_res && $add_res){
            $msg['msg'] = '重建字段成功！';
            return $this->successJson($msg);
        }else{
            $msg['msg'] = '重建字段失败！';
            return $this->errorJson($msg);
        }
    }
    /**
     * @title 批量修改字段（generate）
     * @description 批量修改字段（generate）
     * @author 开发者（宋晓文）
     * @url /generate/Index/generate_edit_field
     **/
    public function generate_edit_field(){
        $input = input();
        $rule = [
            'table_id' => ['require','number'],
            'field_list' => ['require'],
        ];
        $vmsg = [
            'require' => '不能为空',
        ];
        $validate = new \think\Validate($rule,$vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg']='校验失败';
            $msg['validate']=$validate->getError();
            return $this->errorJson($msg);
        }

        $table = Db::table('zb_generate.tp_table')->find($input['table_id']);
        $database = Db::table('zb_generate.tp_model')->find($table['model_id']);
        if(empty($table) || empty($database)){
            $msg['msg']='table_id无可用数据获取';
            return $this->successJson($msg);
        }
        $inp_count = count($input['field_list']);
        $res_count = 0;
        foreach ($input['field_list'] as $k=>$v){
            if (!empty($v['database']) && !empty($v['database']['id'])){
                $res = Db::table('zb_generate.tp_field')->where('id',$v['database']['id'])->update($v['database']);
                if($res){
                    $res_count++;
                }
            }
        }
        if ($res_count == $inp_count){
            $msg['msg'] = '修改成功！';
            return $this->successJson($msg);
        }else{
            $msg['msg'] = '修改失败！';
            $msg['success_count'] = $res_count;
            $msg['input_count'] = $inp_count;
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 修改字段comment
     * @description 修改字段comment
     * @author 开发者（宋晓文）
     * @url /generate/Index/edit_field_comment
     **/
    public function edit_field_comment(){
        $input = input();
        $rule = [
            'id' => ['require','number'],
            'not_null' => ['require','number'],
            'comment' => ['require'],
        ];
        $vmsg = [
            'require' => '不能为空',
        ];
        $validate = new \think\Validate($rule,$vmsg);
        $result = $validate->batch()->check($input);
        if ($result !== true) {
            $msg['msg']='校验失败';
            $msg['validate']=$validate->getError();
            return $this->errorJson($msg);
        }

        $res = Db::table('zb_generate.tp_field')->update(['id'=>$input['id'],'comment'=>$input['comment'],'not_null'=>$input['not_null']]);
        $field = Db::table('zb_generate.tp_field')->find($input['id']);
        $table = Db::table('zb_generate.tp_table')->find($field['table_id']);
        $database = Db::table('zb_generate.tp_model')->find($table['model_id']);
        if(empty($field) || empty($table) || empty($database)){
            $msg['msg']='无可用数据获取';
            return $this->successJson($msg);
        }
        $index_model = new \app\generate\model\Index();
        $database_res = $index_model->edit_field_comment("zb_" . $database['db_name'], $table['table_prefix'] . $table['table_name'], $field);

        if ($res && $database_res){
            $msg['msg'] = '修改成功';
            return $this->successJson($msg);
        }else{
            $msg['msg'] = '修改失败';
            return $this->errorJson($msg);
        }
    }



    //成功、错误返回
    function successJson($data){
        $default = array(
            "status" => true,
            "msg" => "成功",
        );
        $data = array_merge($default, $data);
        return json($data);
    }
    function errorJson($data){
        $default = array(
            "status" => false,
            "msg" => "失败",
        );
        $data = array_merge($default, $data);
        return json($data);
    }

}